package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;

import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.tanhua.autoconfig.templates.OssTemplate;

import com.tanhua.domain.db.UserInfo;

import com.tanhua.domain.mongo.Comment;

import com.tanhua.domain.mongo.Video;

import com.tanhua.domain.vo.PageResult;

import com.tanhua.domain.vo.VideoVo;

import com.tanhua.dubbo.api.db.UserInfoApi;

import com.tanhua.dubbo.api.mongo.CommentApi;

import com.tanhua.dubbo.api.mongo.VideoApi;

import com.tanhua.server.interceptors.UserHolder;

import org.apache.dubbo.config.annotation.DubboReference;

import org.bson.types.ObjectId;

import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;

import java.util.ArrayList;

import java.util.List;

@Service

public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {

//     1、封面图片 上传到阿里云

        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

//     2、小视频 上传到FASTDFS

        String fileName = videoFile.getOriginalFilename();
        String extName = fileName.substring( fileName.lastIndexOf(".")+1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), extName, null);
        String fullPath = storePath.getFullPath();
        String videoUrl = fdfsWebServer.getWebServerUrl() + fullPath;

        Video video = new Video();

//        video.setId(); //ObjectId

//        video.setVid();//雪花算法

//        video.setCreated();//创建时间

        video.setUserId(UserHolder.getUserId());
        video.setText("双11悄悄过去了"); //上传小视频时带的文字，但是现在没有，我们可以随便给一句话
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);

        videoApi.saveVideo(video);

        return ResponseEntity.ok(null);

    }

    // TODO  此时我们直接分页查询小视频表
    //@Cacheable(value = "videoList",key = "#page+'_'+#pagesize")   // 要求：方法的返回结果的类一定要实现序列化接口
    public PageResult queryVideo(Integer page, Integer pagesize) {

        System.out.println("查询小视频--执行了数据库查询");

//        key  value

        PageResult pageResult =  videoApi.queryVideo(page,pagesize);
        List<Video> videoList = (List<Video>) pageResult.getItems();

        List<VideoVo> list= new ArrayList<>();
        for (Video video : videoList) {
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            if(userInfo==null){
                continue; //跳出本次循环  进入下次循环
            }
            VideoVo videoVo = new VideoVo();
            //            把 video+userInfo ---》videoVo
            BeanUtils.copyProperties(video,videoVo);
            videoVo.setId(video.getId().toString());
            videoVo.setCover(video.getPicUrl());
            videoVo.setSignature(video.getText());

            videoVo.setHasLiked(0); //是否点赞
            videoVo.setHasFocus(0); //是否关注博主

            BeanUtils.copyProperties(userInfo,videoVo);
            videoVo.setUserId(userInfo.getId());
            list.add(videoVo);
        }

        pageResult.setItems(list);

        return pageResult;

    }

    public ResponseEntity like(String videoId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(4);
        comment.setUserId(UserHolder.getUserId());

        Integer count = commentApi.save(comment);
        redisTemplate.boundValueOps("video_like_" + UserHolder.getUserId() + "_" + videoId).set("");
        return ResponseEntity.ok(count);
    }

    public ResponseEntity dislike(String videoId) {

        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(4);
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);
        redisTemplate.delete("video_like_"+UserHolder.getUserId()+"_"+videoId);
        return ResponseEntity.ok(count);
    }

}
